import {request} from "../../utils/request";
import config from "../../utils/config";
import {formatTime} from "../../utils/util"

const app = getApp();
Page({
    data: {
        picUrl: config.picUrl,
        url: config.url,
        formData: {album_id: 1},
        header: {'contentType': 'application/x-www-form-urlencoded;charset=utf-8'},
        custom: wx.getMenuButtonBoundingClientRect(),
        user: {},
        title: '求购好剧',
        sku: [], //所有的sku属性,用作页面列表渲染
        id: '', //以下都是商品的属性
        name: '',
        img: '', //商品列表页图片
        brand_id: '', //商家id
        type: 1,
        price: '',
        content: '', //商品文字介绍
        old: '', //商品新旧程度
        previous_box: 1, //是否有原盒 1:-有，2-无
        clue_card: 1, //线索卡是否缺失：1-无缺失；2-有缺失
        play_status: 1, //人物剧本状态：1-完好；2-破损；3-缺失
        status: 1,
        visible: false,
        lang: 'zh_CN',
        skus:[],
        free_freight:1,
        freight:0.00
    },
    onLoad(options) {
        this.getSkus()
        this.setData({user:wx.getStorageSync('userInfo')})
        if ('id' in options) {
            this.setData({id: options.id})
            this.getData()
        }
    },
    onReady(){
        var timer = setInterval(()=>{
            if(wx.getStorageSync('userInfo')){
                this.setData({user:wx.getStorageSync('userInfo')})
                clearInterval(timer)
            }
        },500)

    },
    uploadImg() {
        this.upload(1, res => {
            if (res.code != 200) {
                wx.showToast({title: res.msg, icon: 'none'})
                return false
            }
            this.setData({img: res.data.src})
        })
    },
    delImg() {
        this.setData({img: ''})
    },
    upload(count, callback) {
        wx.showLoading()
        wx.chooseImage({
            count: count,
            sizeType: ['compressed', 'original'],
            success: res => {
                for (let v of res.tempFiles) {
                    wx.uploadFile({
                        url: this.data.url + '/system/api/uploadImage',
                        filePath: v.path,
                        name: 'file',
                        formData: this.data.formData,
                        success: res => {
                            wx.hideLoading()
                            callback(JSON.parse(res.data))
                        }
                    })
                }
            },
            fail: err => {
                wx.hideLoading()
            }
        })

    },
    getSkus() {
        request({url: "/miniprogram/system/getFilterData"}).then(res => {
            this.setData({sku: res.data})
        })
    },
    chooseSku(e) {
        var sku = this.data.skus,
            {type, value, pid} = e.currentTarget.dataset
        value = parseInt(value)
        if (sku.indexOf(value) > -1) {
            sku = sku.filter(item => item != value)
            this.setData({skus: sku})
        } else {
            if (type == 'radio') {
                var tmp1 = this.data.sku.filter(item => item.value == pid),
                    tmp2 = tmp1[0].children.map(item => parseInt(item.value))
                for (let v of tmp2) {
                    var index = sku.indexOf(v)
                    if (index > -1) sku.splice(index, 1)
                }
            }
            sku.push(value)
            this.setData({skus: sku})
        }
    },
    changeValue(e) {
        var field = e.currentTarget.dataset.field,
            value = e.detail.value
        this.setData({[field]: value})
    },
    caogao() {
        this.setData({status: 2})
        this.submit()
    },
    shangjia() {
        this.setData({status: 1})
        this.submit()
    },
    submit() {

        // return false
        var {name,price} = this.data
        if(!name || !price){
            config.toast('带星号的选项为必填项，请填写完整后再进行提交。',201,()=>{})
            return false;
        }
        var sku = this.data.sku,
            tmpSku = [],
            skus = this.data.skus,
            tmpSkus = {} //这是要传到后台的
        for (let v of sku) {
            tmpSku.push({id: v.value, child: v.children.map(item => parseInt(item.value))})
        }
        for (let v of skus) {
            for (let v2 of tmpSku) {
                if (v2.child.indexOf(v) > -1) {
                    if (!tmpSkus[v2.id]) {
                        tmpSkus[v2.id] = [v]
                    } else {
                        tmpSkus[v2.id].push(v)
                    }
                }
            }
        }
        var good = {
            id: this.data.id,
            name: this.data.name,
            type: this.data.type,
            brand_id: this.data.user.id,
            price: this.data.price,
            status: this.data.status,
            img: this.data.img,
            // banner:this.data.bannerList.join(','),
            content: this.data.content,
            skus: this.data.skus,
            // old:this.data.old,
            // previous_box:this.data.previous_box,
            // clue_card: this.data.clue_card,
            // play_status: this.data.play_status,
            is_buy:1, //售卖的商品不用传这个参数，求购的商品要传
            out_trade_no:Date.now().toString() + this.data.user.id,
            free_freight:this.data.free_freight,
            freight: this.data.freight
        }
        var attr = {},banner = []
        wx.showLoading()
        request({
            url: "/miniprogram/good/editGood",
            data: {good, sku: tmpSkus, attr, banner},
            type: 'post'
        }).then(res => {
            wx.hideLoading()
            if(good.status == 2){
                config.toast('草稿保存成功',201,()=>{})
                return false
            }
            request({url:"/miniprogram/good/createBuyOrder",data:{...good},type:'post'}).then(res2=>{
                wx.requestPayment({
                    timeStamp: res2.data.timeStamp,
                    nonceStr: res2.data.nonceStr,
                    package: res2.data.package,
                    signType: res2.data.signType,
                    paySign: res2.data.paySign,
                    success (res3) {
                        config.toast("支付成功",200,()=>{
                            setTimeout(()=>{
                                wx.navigateBack()
                            },1500)
                        })
                    },
                    fail (res4) {
                        config.toast("支付取消",201,()=>{})
                    }
                })

            })
        })
    },
    getData() {
        request({url: '/miniprogram/good/editSubcircle', data: {id: this.data.id}}).then(res => {
            this.setData({
                name: res.data.name,
                img: res.data.img,
                type: res.data.type,
                price: res.data.price,
                content: res.data.content,
                bannerList: res.data.banner.split(','),
                skus: res.data.skus,
                old: res.data.old,
                previous_box: res.data.previous_box,
                clue_card: res.data.clue_card,
                play_status: res.data.play_status,
                status: res.data.status,
            })

        })
    }
})